<template>
  <div
    class="demo-block"
    :class="[blockClass, { hover: hovering }]"
    @mouseenter="hovering = true"
    @mouseleave="hovering = false"
  >
    <div class="source">
      <slot name="source"></slot>
    </div>
    <div class="description" v-if="$slots.default">
      <div class="test"><slot></slot></div>
    </div>

    <div
      class="demo-block-control"
      ref="control"
      :class="{ 'is-fixed': fixedControl }"
    >
      <div class="left">
        <img
          src="./icon/CodeSandbox.svg"
          alt=""
          class="show-code"
          @click="gotoSandBox"
        />
        <img
          src="./icon/codepen.svg"
          alt=""
          class="show-code"
          @click="goCodepen"
        />
      </div>
      <div class="right">
        <img
          src="./icon/code.svg"
          alt=""
          class="show-code"
          @click="isExpanded = !isExpanded"
        />
      </div>
      <!-- <transition name="arrow-slide">
        <i :class="[iconClass, { hovering: hovering }]"></i>
      </transition>
      <transition name="text-slide">
        <span v-show="hovering">{{ controlText }}</span>
      </transition>
      <el-tooltip effect="dark" :content="langConfig['tooltip-text']" placement="right">
        <transition name="text-slide">
          <el-button
            v-show="hovering || isExpanded"
            size="small"
            type="text"
            class="control-button"
            @click.stop="goCodepen">
            {{ langConfig['button-text'] }}
          </el-button>
        </transition>
      </el-tooltip> -->
    </div>

    <div class="meta" ref="meta">
      <div class="highlight">
        <slot name="highlight"></slot>
      </div>
    </div>
  </div>
</template>

<style lang="scss">
.header-anchor {
  display: none;
}
.demo-block {
  border: solid 1px #ebebeb;
  border-radius: 3px;
  transition: 0.2s;

  &.hover {
    box-shadow: 0 0 8px 0 rgba(232, 237, 250, 0.6),
      0 2px 4px 0 rgba(232, 237, 250, 0.5);
  }

  code {
    font-family: Menlo, Monaco, Consolas, Courier, monospace;
    display: inline-block;
  }

  .demo-button {
    float: right;
  }

  .source {
    padding: 24px;
  }

  .meta {
    background-color: #fff;
    border-top: solid 1px #eaeefb;
    overflow: hidden;
    height: 0;
    transition: height 0.2s;
  }

  .description {
    padding: 20px;
    position: relative;
    &::after {
      content: "";
      width: 100%;
      height: 1px;
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      background: #ddd;
    }
    .test {
      display: inline-block;
      background: #fff;
      position: relative;
      z-index: 2;
      padding: 0 4px;
    }
    code {
      background: #f6f7f9;
      color: #d76868;
      padding: 2px 4px;
      border-radius: 2px;
      margin: 0 2px;
    }
  }

  .highlight {
    margin: 15px;
    pre {
      margin: 0;
    }

    code {
      display: block;
    }
    code.hljs {
      margin: 0;
      border: none;
      max-height: none;
      border-radius: 0;

      &::before {
        content: none;
      }
    }
  }

  .demo-block-control {
    border-top: dashed 1px #eaeefb;
    height: 44px;
    box-sizing: border-box;
    background-color: #fff;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    margin-top: -1px;
    position: relative;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    .show-code {
      cursor: pointer;
    }
  }
}
</style>

<script type="text/babel">
import compoLang from "../i18n/component.json";
import Element from "../../index";
import { stripScript, stripStyle, stripTemplate } from "../util";
import { getParameters } from "codesandbox/lib/api/define";
import { getIndexHtml, getMainJs, getPackageJson } from "./code";

const { version } = Element;

export default {
  data() {
    return {
      codepen: {
        script: "",
        html: "",
        style: "",
      },
      hovering: false,
      isExpanded: false,
      fixedControl: false,
      scrollParent: null,
    };
  },

  methods: {
    gotoSandBox() {
      let html = this.codepen.html;
      let tagName = "script";
      let script = `<${tagName}>
        ${this.codepen.script}
    </${tagName}>`;

      const parameters = getParameters({
        files: {
          "src/App.vue": {
            content: Object.values([html, script]).join("\n"),
          },
          "src/main.js": {
            content: getMainJs(),
          },
          "public/index.html": {
            content: getIndexHtml(),
          },
          "package.json": getPackageJson(),
        },
      });
      const url = `https://codesandbox.io/api/v1/sandboxes/define?parameters=${parameters}`;
      window.open(url);
    },
    goCodepen() {
      // since 2.6.2 use code rather than jsfiddle https://blog.codepen.io/documentation/api/prefill/
      const { script, html, style } = this.codepen;
      const resourcesTpl = `<scr${"ipt"} src="https://fastly.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.min.js"></scr${"ipt"}>
    <scr${"ipt"} src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.js"></scr${"ipt"}>
    <scr${"ipt"} src="https://test.wdp.waper4.com/template/index.js"></scr${"ipt"}>`;
      let jsTpl = (script || "").replace(/export default/, "var Main =").trim();
      let htmlTpl = `${resourcesTpl}\n<div id="app">\n${html.trim()}\n</div>`;
      let cssTpl = `@import url("//unpkg.com/element-ui@${version}/lib/theme-chalk/index.css");\n${(
        style || ""
      ).trim()}\n`;
      jsTpl = jsTpl
        ? jsTpl + "\nvar Ctor = Vue.extend(Main)\nnew Ctor().$mount('#app')"
        : "new Vue().$mount('#app')";
      const data = {
        js: jsTpl,
        css: cssTpl,
        html: htmlTpl,
      };
      const form =
        document.getElementById("fiddle-form") ||
        document.createElement("form");
      while (form.firstChild) {
        form.removeChild(form.firstChild);
      }
      form.method = "POST";
      form.action = "https://codepen.io/pen/define/";
      form.target = "_blank";
      form.style.display = "none";

      const input = document.createElement("input");
      input.setAttribute("name", "data");
      input.setAttribute("type", "hidden");
      input.setAttribute("value", JSON.stringify(data));

      form.appendChild(input);
      document.body.appendChild(form);

      form.submit();
    },

    scrollHandler() {
      const { top, bottom, left } = this.$refs.meta.getBoundingClientRect();
      this.fixedControl =
        bottom > document.documentElement.clientHeight &&
        top + 44 <= document.documentElement.clientHeight;
      // this.$refs.control.style.left = this.fixedControl ? `${left}px` : "0";
    },

    removeScrollHandler() {
      this.scrollParent &&
        this.scrollParent.removeEventListener("scroll", this.scrollHandler);
    },
  },

  computed: {
    lang() {
      return this.$route.path.split("/")[1];
    },

    langConfig() {
      return compoLang.filter((config) => config.lang === "zh-CN")[0][
        "demo-block"
      ];
    },

    blockClass() {
      return `demo-${this.lang} demo-${this.$router.currentRoute.path
        .split("/")
        .pop()}`;
    },

    iconClass() {
      return this.isExpanded ? "el-icon-caret-top" : "el-icon-caret-bottom";
    },

    controlText() {
      return this.isExpanded
        ? this.langConfig["hide-text"]
        : this.langConfig["show-text"];
    },

    codeArea() {
      return this.$el.getElementsByClassName("meta")[0];
    },

    codeAreaHeight() {
      if (this.$el.getElementsByClassName("description").length > 0) {
        return (
          this.$el.getElementsByClassName("description")[0].clientHeight +
          this.$el.getElementsByClassName("highlight")[0].clientHeight +
          20
        );
      }
      return this.$el.getElementsByClassName("highlight")[0].clientHeight;
    },
  },

  watch: {
    isExpanded(val) {
      this.codeArea.style.height = val ? `${this.codeAreaHeight + 1}px` : "0";
      if (!val) {
        this.fixedControl = false;
        this.$refs.control.style.left = "0";
        this.removeScrollHandler();
        return;
      }
      setTimeout(() => {
        this.scrollParent = document.querySelector(
          ".page-component__scroll > .el-scrollbar__wrap"
        );
        this.scrollParent &&
          this.scrollParent.addEventListener("scroll", this.scrollHandler);
        this.scrollHandler();
      }, 200);
    },
  },

  created() {
    const highlight = this.$slots.highlight;
    if (highlight && highlight[0]) {
      let code = "";
      let cur = highlight[0];
      if (cur.tag === "pre" && cur.children && cur.children[0]) {
        cur = cur.children[0];
        if (cur.tag === "code") {
          code = cur.children[0].text;
        }
      }
      if (code) {
        this.codepen.html = stripTemplate(code);
        this.codepen.script = stripScript(code);
        this.codepen.style = stripStyle(code);
      }
    }
  },

  mounted() {
    this.$nextTick(() => {
      let highlight = this.$el.getElementsByClassName("highlight")[0];
      if (this.$el.getElementsByClassName("description").length === 0) {
        highlight.style.width = "100%";
        highlight.borderRight = "none";
      }
    });
  },

  beforeDestroy() {
    this.removeScrollHandler();
  },
};
</script>
